package com.chennan.work.jiuqi;

public class JSONFormatter {
	
	public static String format(String content) {
		if (content == null) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		int count = 0;
		boolean inString = false;
		String tab = "\t";
		for (int i = 0; i < content.length(); i++) {
			char ch = content.charAt(i);
			switch (ch) {
			case '{':
			case '[':
				sb.append(ch);
				if (!inString) {
					sb.append("\n");
					count++;
					for (int j = 0; j < count; j++) {
						sb.append(tab);
					}
				}
				break;
			case '\uFEFF': // 非法字符
				if (inString)
					sb.append(ch);
				break;
			case '}':
			case ']':
				if (!inString) {
					count--;
					sb.append("\n");
					for (int j = 0; j < count; j++) {
						sb.append(tab);
					}

					sb.append(ch);
				} else {
					sb.append(ch);
				}
				break;
			case ',':
				sb.append(ch);
				if (!inString) {
					sb.append("\n");
					for (int j = 0; j < count; j++) {
						sb.append(tab);
					}
					sb.append(' ');
				}
				break;
			case ':':
				sb.append(ch);

				if (!inString) {
					sb.append(' ');
				}
				break;
			case ' ':
			case '\n':
			case '\t':
				if (inString) {
					sb.append(ch);
				}
				break;
			case '"':
				if (i > 0 && content.charAt(i - 1) != '\\') {
					inString = !inString;
				}
				sb.append(ch);
				break;
			default:
				sb.append(ch);
				break;
			}
		}
		return sb.toString();
	}
}
